package net.hailxenu.stats;

import java.io.File;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.logging.Level;

public class Updater implements Runnable
{
    private XenuStats plugin;
    private Configuration xsconf;
    public BufferedReader reader;
    public BufferedWriter writer;
    private Integer updateTime;
    private String host;
    private int port;

    public Updater(final XenuStats plugin)
    {
        try
        {
            this.plugin = plugin;
            File xstatsprop = new File("xstats.properties");
            if(!xstatsprop.exists())
            {
                FileWriter fw = new FileWriter(xstatsprop);
                fw.write("broadcast-ip: is.xenustats.com\n" +
                         "broadcast-port: 25564\n" +
                         "apikey: \n" +
                         "updateTime: 240\n");
                fw.close();
            }
            this.xsconf = new Configuration(xstatsprop);
            updateTime = xsconf.getInt("updateTime");
            if(updateTime < 240)
            {
                updateTime = 240;
                plugin.logger.info("[" + plugin.pluginName + "] Minimum update time was invalid - fixed by plugin.");
            }

            host = (xsconf.hasKey("broadcast-ip") ? xsconf.getString("broadcast-ip") : "is.xenustats.com");
            port = (xsconf.hasKey("broadcast-port") ? xsconf.getInt("broadcast-port") : 25564);
        } catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void run()
    {
        try
        {
            plugin.logger.info("[" + plugin.pluginName + "] Connecting to " + host + ":" + port + ".");

            plugin.sock = new Socket(host, port);
            reader = new BufferedReader(new InputStreamReader(plugin.sock.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(plugin.sock.getOutputStream()));

            writer.write("AUTH " + xsconf.getString("apikey") + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
            writer.flush();
            while(plugin.sock.isConnected())
            {
                Thread.sleep(updateTime * 1000);

                plugin.logger.info("[" + plugin.pluginName + "] Updating stats.");

                HashMap<String, PlayerData> pd = (HashMap<String, PlayerData>) plugin.playerData.clone();

                writer.write("startupdate\n");
                writer.flush();

                for(PlayerData pd2 : pd.values())
                {
                    if(pd2.doClearIfPossible())
                    {
                        plugin.playerData.remove(pd2.getName());
                    } else {
                        writer.write(pd2.getOutput() + "\n");
                        writer.flush();
                        pd2.setZero();
                    }
                }
                
                plugin.logger.info("[" + plugin.pluginName + "] Updating stats complete.");
            }
        } catch(Exception e)
        {
            e.printStackTrace();
            plugin.logger.log(Level.INFO, "[" + plugin.pluginName + "] Error while attempting connect, retrying in 15 seconds...");
            try
            {
                Thread.sleep(15000);
                run();
            } catch(Exception ex)
            {

            }
        }
    }
}